#include "ClientPlayer.h"

ClientPlayer *Self = new ClientPlayer;

ClientPlayer::ClientPlayer()
{
    setObjectName("ClientPlayer");

    socket = new QTcpSocket(this);
    connect(socket, SIGNAL(connected()), this, SLOT(sendPlayerInfo()));
    connect(socket, SIGNAL(connected()), this, SIGNAL(onConnected()));
    connect(socket, SIGNAL(readyRead()), this, SLOT(receiveNotification()));
}

void ClientPlayer::connectToServer(const QString &server_address, qint16 port){
    if(!socket->isValid()){
        socket->connectToHost(server_address, port);
    }else{
        emit occurError(tr("You are already connected to a certain server."));
    }
}

void ClientPlayer::chat(const QString &message){
    notify(Chat, message);
}

void ClientPlayer::sendPlayerInfo(){
    notify(NewPlayer, player_name);
}

void ClientPlayer::movePiece(int from, int to){
    QString msg = QString("%1 %2").arg(from).arg(to);
    notify(MovePiece, msg);
}

void ClientPlayer::receiveNotification(){
    qDebug() << "ClientPlayer: receiving...";
    while(socket->canReadLine()){
        QByteArray line = socket->readLine();
        line.remove(line.length() - 1, 1);

        int i = line.indexOf('=');
        if(i <= 0){
            qDebug() << "ClientPlayer: Illegal Message";
            return;
        }

        CommandType command = CommandType(line.left(i).at(0) - '0');
        QByteArray data = QByteArray::fromBase64(line.mid(i + 1));

        switch(command){
        case Chat:{
            i = data.indexOf(' ');
            if(i > 0){
                emit onChat(QString::fromUtf8(data.mid(0, i)), QString::fromUtf8(data.mid(i + 1)));
            }else{
                emit onChat(QString(), QString::fromUtf8(data));
            }
            break;
        }
        case MovePiece:{
            QList<QByteArray> pos = data.split(' ');
            int player_id = pos.at(0).toInt();
            int from = pos.at(1).toInt();
            int to = pos.at(2).toInt();
            emit onMovePiece(player_id, from, to);
            break;
        }
        case SetProperty:{
            int i = data.indexOf(' ');
            QByteArray p_key = data.left(i);
            QString p_value = QString::fromUtf8(data.mid(i + 1));
            setProperty(p_key.data(), p_value);
            emit onUpdatePlayer(player_id, QString("%1 %2").arg(QString::fromUtf8(p_key)).arg(p_value));
            break;
        }
        case NewPlayer:{
            i = data.indexOf(' ');
            int player_id = data.left(i).toInt();
            QString player_name = data.mid(i + 1);
            emit onNewPlayer(player_id, player_name);
            break;
        }
        case SetPlayer:{
            qDebug() << "SetPlayer" << data;
            i = data.indexOf(' ');
            int player_id = data.left(i).toInt();
            QString property = data.mid(i + 1);
            emit onUpdatePlayer(player_id, property);
            break;
        }
        case NoAction:default:;
        }
    }
}
